﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using Microsoft.SharePoint;

namespace SharePoint.Intranet.OpmlGenerator
{
    public class OpmlPage : System.Web.UI.Page
    {
        protected override void OnPreLoad(EventArgs e)
        {
            XmlDocument opmlFile = new XmlDocument();
            XmlElement opmlTag = opmlFile.CreateElement("opml");
            AddXmlAttribute(ref opmlTag, "version", "1.0");

            // Get the list to work with
            SPWeb web = SPContext.Current.Web;
            SPList list = web.Lists[new Guid(Request.QueryString["list"])];

            // Generate the head of the document
            XmlElement headTag = opmlFile.CreateElement("head");
            XmlElement titleTag = opmlFile.CreateElement("title");
            titleTag.InnerText = list.Title;
            headTag.AppendChild(titleTag);
            opmlTag.AppendChild(headTag);

            // build the body of the document
            XmlElement bodyTag = opmlFile.CreateElement("body");

            SPListItemCollection items = list.Items;
            for (Int32 i = 0; i < items.Count; i ++)
            {
                XmlElement outlineTag = opmlFile.CreateElement("outline");
                AddXmlAttribute(ref outlineTag, "text", items[i].Title);
                AddXmlAttribute(ref outlineTag, "title", items[i].Title);
                AddXmlAttribute(ref outlineTag, "type", "rss");
                SPFieldUrlValue htmlUrlValue = new SPFieldUrlValue(items[i]["Blog URL"].ToString());
                AddXmlAttribute(ref outlineTag, "htmlUrl", htmlUrlValue.Url);
                SPFieldUrlValue rssUrlValue = new SPFieldUrlValue(items[i]["RSS URL"].ToString());
                AddXmlAttribute(ref outlineTag, "xmlUrl", rssUrlValue.Url);

                bodyTag.AppendChild(outlineTag);
            }
            opmlTag.AppendChild(bodyTag);

            // send the XML to the client
            Response.ContentType = "text/xml";
            Response.AppendHeader("content-disposition", string.Format("attachment; filename={0}.xml", list.Title));
            opmlFile.AppendChild(opmlTag);
            opmlFile.Save(Response.OutputStream);

        }




        private void AddXmlAttribute(ref XmlElement node, string attributeName, string attributeValue)
        {
            XmlAttribute xmlAttr = node.OwnerDocument.CreateAttribute(attributeName);
            xmlAttr.Value = attributeValue;
            node.Attributes.Append(xmlAttr);
        }
    }
}
